package Exam.impl;

import Exam.dao.PhoneAddressDao;
import Exam.domain.PhoneAddress;
import Exam.utils.JDBCutil;
import JDBC.JDBCUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class PhoneAddressImpl implements PhoneAddressDao {

    @Override
    public boolean addphone(PhoneAddress p) {
        String sql="insert into phoneaddress(name,phonenum,position,company) values(?,?,?,?)";
        String str[]={p.getName(),p.getPhonenum(),p.getPosition(),p.getCompany()};
     int result = JDBCutil.excuteupdate(sql,str);
        if(result==1){
            return true;
        }
        return false;
    }

    @Override
    public boolean deletephone(String name) {
        String sql = "delete from phoneaddress where name=?";
        String str[]={name};
        int result = JDBCutil.excuteupdate(sql,str);
        if(result>=1){
            return  true;
        }
        return false;
    }

    @Override
    public ArrayList<PhoneAddress> selectAll() {
        ArrayList<PhoneAddress> arr=  new ArrayList<>();
        String sql = "select * from phoneaddress";
        ResultSet rs = JDBCutil.excuteQuery(sql);
        try {
            while(rs.next()){
            arr.add(new PhoneAddress(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5)));

        }  } catch (SQLException e) {
                e.printStackTrace();
            }


        return arr;
    }

    @Override
    public PhoneAddress selectOneByname(String name) {
        PhoneAddress p = new PhoneAddress();
        String sql="select * from phoneaddress where name=?";
        ResultSet rs = JDBCutil.excuteQuery(sql,name);
        try {
            while(rs.next()){
            p=new PhoneAddress(rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5));


        }     } catch (SQLException e) {
               e.printStackTrace();
            }


        return p;
    }

    @Override
    public boolean updatephone(PhoneAddress p) {
        String sql = "update phoneaddress set name=?,phonenum=?,position=?,company=? where id=?";
        String str[]={p.getName(),p.getPhonenum(),p.getPosition(),p.getCompany(),p.getId()};
        int result=JDBCutil.excuteupdate(sql,str);
        if(result==1){
            return true;
        }
        return false;
    }
}
